/**
 * Created by meiguizhinian on 2018/7/6
 * Copyright © 2018 lixiaolong. All rights reserved.
 */

//cocos2dx class
unblockme.GameScene = LLScene.extend({
	res : [
		"res/game/UnblockMe/NETDATA/ANIMATION/Game.actor",

		"res/game/UnblockMe/vfs/bg_game.png",
		"res/game/UnblockMe/vfs/pause.png",
		"res/game/UnblockMe/vfs/help.png",
		"res/game/UnblockMe/vfs/magnifying.png",
		"res/game/UnblockMe/vfs/regret.png",
		"res/game/UnblockMe/vfs/replay.png",
		"res/game/UnblockMe/vfs/text_box.png",
		"res/game/UnblockMe/vfs/television.png",
		"res/game/UnblockMe/vfs/map4x4.png",
		"res/game/UnblockMe/vfs/map5x5.png",
		"res/game/UnblockMe/vfs/map6x6.png",
		"res/game/UnblockMe/vfs/exit.png",
		"res/game/UnblockMe/vfs/wood_red_2x1.png",
		"res/game/UnblockMe/vfs/wood_yellow_1x2.png",
		"res/game/UnblockMe/vfs/wood_yellow_1x3.png",
		"res/game/UnblockMe/vfs/wood_yellow_2x1.png",
		"res/game/UnblockMe/vfs/wood_yellow_3x1.png",
		"res/game/UnblockMe/vfs/arrow.png",
		//font
		"res/fonts/1num_0.png",
		"res/fonts/1num.fnt",
		//audio
		"res/game/UnblockMe/audio/effect/return.mp3",
		"res/game/UnblockMe/audio/effect/hitcoll.mp3",
		"res/game/UnblockMe/audio/effect/victory.mp3",
		"res/game/UnblockMe/audio/effect/victory3.mp3",
		"res/game/UnblockMe/audio/effect/regret.mp3",
		"res/game/UnblockMe/audio/effect/replay.mp3",
		"res/game/UnblockMe/audio/effect/combo.mp3",
		//data
		"res/game/UnblockMe/data/gate.csv",
	],

	ctor: function (form, space=null) {
		this._super(form, space);

		this._unblockMe = new jssupport.UnblockMe();

		let button_pause = this._formNode.getChildByName("bt1");
		button_pause.setTouchEndCallback(function() {
			let dialog = unblockme.PauseDialog.create("Pause");
			this.showDialog(dialog);
		}.bind(this));
		//帮助
		let button_helper = this._formNode.getChildByName("bt2");
		button_helper.setTouchEndCallback(function() {
			let count = unblockme.Recorder.getMagnifyingCount();
			if (count===0) {

			} else {
				//Advertise::addAppealCount();
				unblockme.Recorder.addMagnifyingCount(-1);
				this._updateMagnifyingLabel();
				if (this._unblockMe.step.size()!==0) {
					this.select(this._gate);
				}
				//指导玩家从头走到尾
				this.showTeachingLayer();
				this._teachStep();
			}
		}.bind(this));
		//后退一步
		let button_regret = this._formNode.getChildByName("bt3");
		button_regret.setTouchEndCallback(function() {
			this._regretStep();
		}.bind(this));
		//重玩
		let button_replay = this._formNode.getChildByName("bt4");
		button_replay.setTouchEndCallback(function() {
			this.select(this._gate);
		}.bind(this));
		//观看视频奖励
		let button_reward = this._formNode.getChildByName("bt5");
		button_reward.setTouchEndCallback(function() {
			//advertise 7.游戏中视频免费送一次提示，调视频video
			//Advertise::showVideo("video", Advertise::REWARDID_0);
		});
		//button_reward.setVisible(IvySDK::hasRewardAd("video"));
		this._updateMagnifyingLabel();
	},

	clear : function() {
		this._gate = 0;
		this._unblockMe.clear();

		this._touchMoved = false;
		this._touchBeganTime = 0;
		this._layer = null;
	},

	onEnter : function() {
		this._super();
		//advertise 2.游戏中和选关界面加上banner
		// if (IvySDK::hasBanner("default")) {
		// 	IvySDK::showBanner("default", IvySDK::AD_POS_MIDDLE_BOTTOM);
		// }
		// Advertise::countPlayTime(true);
	},
	onExit : function() {
		// IvySDK::closeBanner(); //关闭banner广告
		// Advertise::countPlayTime(false);
		this._super();
	},

	advertiseReward : function(success, rewardId) {
		// if (success && rewardId==Advertise::REWARDID_0) {
		// 	Recorder::addMagnifyingCount();
		// 	_updateMagnifyingLabel();
		// }
		// if (!success && rewardId==Advertise::REWARDID_1) {
		// 	Advertise::showFull(IvySDK::AD_POS_GAME_PASSLEVEL);
		// }
	},

	select : function(gate=0) {
		this.clear();
		this._gate = gate%unblockme.Recorder.getGateSize();

		let row = unblockme.Recorder.getGateData(this._gate);

		this._unblockMe = new jssupport.UnblockMe();
		this._unblockMe.setMap(row[0]);
		this._unblockMe.setHandbook(row[1]);

		this._updateGateLabel(this._gate);
		this._updateStepLabel(0);
		this._updateBestLabel(this._unblockMe.getHandbookSteps().size() + unblockme.GameScene.userMoveRedWood);
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		let map_bg = this._formNode.getChildByName("or5");
		map_bg.removeAllChildren();
		// 创建地图
		let map_sp = new cc.Sprite(cc.formatStr("vfs/map%dx%d.png", this._unblockMe.getSize().width, this._unblockMe.getSize().height));
		map_bg.addChild(map_sp);

		let map_sp_size = map_sp.getContentSize();
		let w = map_sp_size.width-120;
		let h = map_sp_size.height-120;
		w = jssupport.NumberHelper.integer_multiple_ceil(w, this._unblockMe.getSize().width);
		h = jssupport.NumberHelper.integer_multiple_ceil(h, this._unblockMe.getSize().height);
		//地图上创建一个层，方便管理木块位置
		let layer = new cc.LayerColor(cc.color(255,255,255,0), w, h);  //4边空白是60
		layer.ignoreAnchorPointForPosition(false);
		layer.setPosition(map_sp_size.width/2, map_sp_size.height/2);
		map_sp.addChild(layer);
		this._layer = layer;

		let uw = w/this._unblockMe.getSize().width;
		let uh = h/this._unblockMe.getSize().height;

		this._unblockMe.play(w, h, uw, uh);
		//添加出口
		let exit_sp = new cc.Sprite("vfs/exit.png");
		exit_sp.setAnchorPoint(cc.p(0, 0));
		map_sp.addChild(exit_sp);
		exit_sp.setPosition(this._unblockMe.getExit().x*uw+60-5, this._unblockMe.getExit().y*uh+60);
		// 添加木块
		for (let i=0; i!==this._unblockMe.living.children.array.length; ++i) {
			let wood = this._unblockMe.living.children.array[i];
			let size = cc.size(wood.width, wood.height);
			//为了修正木块大小不一致的问题，先添加一个node，木块各自挂在node上
			let node = new cc.Node();
			let name = wood.name;
			node.setName(name);
			node.setContentSize(size);
			node.setPosition(wood.x, wood.y);
			layer.addChild(node);

			let filename = "";
			if (name==='A') {
				filename = "wood_red_2x1";
			} else {
				filename = cc.formatStr("wood_yellow_%dx%d", (wood.width/uw), (wood.height/uh));
			}
			let wood_sp = new cc.Sprite("vfs/"+filename+".png");
			wood_sp.setPosition(size.width/2, size.height/2);  //放到父节点中间
			node.addChild(wood_sp);

			let listener = {
				event : cc.EventListener.TOUCH_ONE_BY_ONE,
				swallowTouches : true,
			};
			listener.onTouchBegan = function(t, e) {
				let node = e.getCurrentTarget();
				let location = node.getParent().convertToNodeSpace(t.getLocation());
				if (cc.rectContainsPoint(node.getBoundingBox() ,location)) {
					//判断木块是否可以移动
					let name = node.getName();
					let moveable = false;
					if (node.getContentSize().width>node.getContentSize().height) {
						moveable = this._unblockMe.living.moveChildLeftOrRightEnable(name);
					} else {
						moveable = this._unblockMe.living.moveChildUpOrDownEnable(name);
					}
					if (moveable) {
						this._touchMoved = false;
						this._touchBeganTime = (new Date()).getTime();
						this._touchStartPostion = node.getPosition();

						//移动计数
						let step = cc.p(node.getPositionX(), node.getPositionY());
						step.name = name;
						this._unblockMe.step.push(step);
						return true;
					}
					return false;
				}
				return false;
			}.bind(this);
			listener.onTouchMoved = function(t, e) {
				//移动木块
				let node = e.getCurrentTarget();
				let size = node.getContentSize();
				let pos = node.getPosition();

				let name = node.getName();
				let vec = cc.pSub(t.getLocation(), t.getPreviousLocation());
				//判断是否发生了移动
				if (size.width > size.height) {
					if (vec.x === 0) {
						return;
					}
					this._touchMoved = this._unblockMe.living.moveChildLeftOrRight(name, vec.x, false, pos);
				} else {
					if (vec.y === 0) {
						return;
					}
					this._touchMoved = this._unblockMe.living.moveChildUpOrDown(name, vec.y, false, pos);
				}
				if (this._touchMoved) {
					node.setPosition(pos);
				} else if (unblockme.GameScene.userMoveRedWood===1) {
					if (name==='A') {
						//判断是否移动到最右边
						if (this._unblockMe.living.adjacent_to_child_right(name)) {
							cc.eventManager.removeListeners(node);
							this._updateStepLabel(this._unblockMe.step.size());
							this._onSuccess();
						}
					}
				}
			}.bind(this);
			listener.onTouchEnded = function(t, e) {
				let node = e.getCurrentTarget();
				let size = node.getContentSize();
				let pos = node.getPosition();
				let vec = cc.pSub(t.getLocation() , t.getStartLocation());

				let name = node.getName();
				if (name==='A') {//最后移动红色木块时，只要碰一下就判断是否可以成功
					// 检查是否移动成功
					if (this._unblockMe.living.moveChildToFarRightEnable(name)) {
						cc.eventManager.removeListeners(node);
						this._updateStepLabel(this._unblockMe.step.size());
						this._onSuccess();
						return;
					}
				}
				if (this._touchMoved) {
					//吸附木块位置到网格点
					let back = false;
					if (size.width > size.height) {
						back = this._unblockMe.living.suckChildLeftOrRight(name, vec.x, 10, pos);
					} else {
						back = this._unblockMe.living.suckChildUpOrDown(name, vec.y, 10, pos);
					}

					if (!back) {
						//计算加速度
						let aa = 0;
						let dt = ((new Date()).getTime()-this._touchBeganTime);
						if (size.width > size.height) {
							let a = vec.x*2/(dt*dt);
							if (Math.abs(a)>200000) {//加速很大，所以移动距离加长
								aa = this._unblockMe.living.box.size.w;
								if (a<0) {
									aa *= -1;
								}
							} else {
								aa = vec.x/Math.abs(vec.x);
							}
							this._unblockMe.living.moveChildLeftOrRight(name, aa, true, pos);
						} else {
							let a = vec.y*2/(dt*dt);
							if (Math.abs(a)>200000) {//加速很大，所以移动距离加长
								aa = this._unblockMe.living.box.size.h;
								if (a<0) {
									aa *= -1;
								}
							} else {
								let xx = vec.y;
								aa = xx/Math.abs(xx);
							}
							this._unblockMe.living.moveChildUpOrDown(name, aa, true, pos);
						}
					}
					this._onTouchEnded(node, this._touchStartPostion,pos);
				} else {
					this._onTouchEnded(node, this._touchStartPostion,pos);
				}
			}.bind(this);
			cc.eventManager.addListener(cc.EventListener.create(listener), node);
		}
	},
	////////////////////////////////////////////////////////////////////////////////////////////////////////////
	_onTouchEnded : function(node, fromPos, toPos) {
		let s_1 = this._unblockMe.step.back();
		s_1.x = toPos.x-s_1.x;
		s_1.y = toPos.y-s_1.y;
		if (s_1.x===0 && s_1.y===0) {
			this._unblockMe.step.pop();
		}
		this._updateStepLabel(this._unblockMe.step.size());
		this._moveWood(node, fromPos, toPos, true);
	},

	_moveWood : function(node, fromPos, toPos, stopedCheck) {
		let curPos = node.getPosition();
		if (cc.pointEqualToPoint(curPos, toPos)) {
			let vec = cc.pSub(toPos, fromPos);
			if (vec.x===0 && vec.y===0) {//不需要碰撞回弹效果
				this._onWoodStoped(node);
			} else {//木块移动到边界回弹效果
				let pos = cc.p(0, 0);
				let size = node.getContentSize();
				if (size.width>size.height) {
					if (vec.x>0) {
						pos.x = -10;
					} else {
						pos.x = 10;
					}
				} else {
					if (vec.y>0) {
						pos.y = -10;
					} else {
						pos.y = 10;
					}
				}
				//cc.log("pos(%f,%f) vec(%f,%f)\n",pos.x, pos.y, vec.x,vec.y);
				let move1 = cc.moveBy(0.1, pos);
				let move2 = move1.reverse();
				let call = cc.callFunc(function(){
					if (stopedCheck) {
						this._onWoodStoped(node);
					}
				}.bind(this));
				node.runAction(cc.sequence(move1, move2, call));
			}
		} else {
			let move = cc.moveTo(0.2, toPos).easing(cc.easeBounceOut());
			let call = cc.callFunc(function(){
				if (stopedCheck) {
					this._onWoodStoped(node);
				}
			}.bind(this));
			node.runAction(cc.sequence(move, call));
		}
	},

	_onWoodStoped : function(node) {
		ivy.SoundManager.getInstance().playSound("audio/effect/hitcoll.mp3");
		let name = "A";
		if (unblockme.GameScene.userMoveRedWood) {
			//判断是否移动到最右边
			if (!this._unblockMe.living.adjacent_to_child_right(name)) {
				this._teachIf(node);
				return;
			}
		} else {
			// 检查是否移动成功
			if (!this._unblockMe.living.moveChildToFarRightEnable(name)) {
				// 未成功，判断是否在教学模式中
				this._teachIf(node);
				return;
			}
		}
		this._onSuccess();
	},

	_onSuccess : function() {
		//成功
		//保存进度
		let best = this._saveProgress(!!this._teachingLayer);
		//成功音效
		if (best>=3) {
			ivy.SoundManager.getInstance().playSound("audio/effect/victory3.mp3");//3星过关音效
		} else {
			ivy.SoundManager.getInstance().playSound("audio/effect/victory.mp3");//过关音效
		}
		if (this._teachingLayer) {
			this.hideTeachingLayer();
		}

		let showGate = this._gate+1;
		if (showGate<10) {//3.前10关不加广告，第10关结束添加评分引导

		} else if (showGate===10) {//3.前10关不加广告，第10关结束添加评分引导

		} else if (showGate===11) {//4.第11关必弹视频video广告
			//Advertise::showVideo("video1", Advertise::REWARDID_1);
		} else {
			// if (Advertise::isFirstPass) {
			// 	//8.老玩家每次进入游戏，第一次过关后，必弹视频广告
			// 	Advertise::showVideo("video1", Advertise::REWARDID_1);
			// 	Advertise::resetCountPlayTime();
			// } else {
			// 	Advertise::showFullOnSuccess = true;
			// }
		}
		//Advertise::isFirstPass = false;
		if (showGate===10) {
			let rate = unblockme.RateDialog.create("Rate");
			rate.setOnExitCallback(function(){
				this._replaceByOverScene(best);
			}.bind(this));
			this.showDialog(rate);
		} else {
			this._replaceByOverScene(best);
		}
	},

	_saveProgress : function(isTeaching) {
		unblockme.Recorder.setProgress(this._gate+1);
		let count = this._unblockMe.step.size();//移动步数
		let best = this._unblockMe.getHandbookSteps().size()+unblockme.GameScene.userMoveRedWood;
		let rank = unblockme.Recorder.calculateStarCountByStepCount(count,best);
		if (!isTeaching && rank===4 && unblockme.Recorder.getGateStarCount(this._gate)!==4) {//获得放大镜奖励
			unblockme.Recorder.addMagnifyingCount();
		}
		unblockme.Recorder.setGateStarCount(this._gate, rank);
		return rank;
	},

	_replaceByOverScene : function(best) {
		this.showTouchShieldLayer();
		//移动木块a出去
		let nodeA = this._layer.getChildByName("A");

		let visibleSize = cc.director.getVisibleSize();
		let move = cc.moveBy(1, visibleSize.width ,0).easing(cc.easeIn(1));
		let call = cc.callFunc(function(){
			cc.LoaderScene.preload(unblockme.OverScene.prototype.res, function () {
				let scene = unblockme.OverScene.create("Over");
				scene.setStars(best);
				cc.director.runScene(scene);
			}, this);
		});
		nodeA.runAction(cc.sequence(move,call));
	},

	_teachIf : function(node) {
		if (this._teachingLayer) {
			let pos = node.getParent().convertToWorldSpace(node.getPosition());
			let rect = cc.rect(pos.x, pos.y, node.getContentSize().width, node.getContentSize().height);
			let frame = this._teachingLayer.getEndFrame();
			if (cc.rectEqualToRect(frame, rect)) {
				this._teachStep();//如果移动到目标位置，下一步
			} else {
				let name = node.getName();
				if (!this._unblockMe.step.empty() && this._unblockMe.step.back().name===name) {
					this._regretStep();//如果未移动到目标位置，后退一步
				}
			}
		}
	},
	_teachStep : function() {
		if (!this._teachingLayer) {
			return;
		}
		let idx = this._unblockMe.step.size();
		let steps = this._unblockMe.getHandbookSteps();
		if (idx>=steps.size()) {//handbook 数据不包括最后移动红色木块走法，所以超出索引一定是移动最后红色木块
			if (unblockme.GameScene.userMoveRedWood) {//设定最后一步由用户手动移出红色木块的情况下会多出一步
				let name = "A";

				let vecA = cc.p(0, 0);
				vecA.y = 0;//y不需要移动
				vecA.x = this._unblockMe.living.distance_at_child_right(name)/this._unblockMe.living.unit.width;
				vecA.name = name;
				this._teachStepVec(vecA);
			}
		} else {
			let vec = steps.get(idx);
			this._teachStepVec(vec);
		}
	},
	_teachStepVec : function(vec) {
		let node = this._layer.getChildByName(vec.name);

		let pos = node.getPosition();
		let size = node.getContentSize();
		let world_pos = node.getParent().convertToWorldSpace(pos);
		let rect = cc.rect(world_pos.x, world_pos.y, size.width, size.height);
		this._teachingLayer.demos(rect, cc.p(vec.x*this._unblockMe.living.unit.width, vec.y*this._unblockMe.living.unit.height));
	},

	_regretStep : function() {
		if (this._unblockMe.step.size()===0) {
			return;
		}
		let step = this._unblockMe.step.back();
		this._unblockMe.living.moveChildOrigin(step.name, cc.p(-step.x, -step.y));
		let node = this._layer.getChildByName(step.name);
		let pos = node.getPosition();
		pos.x -= step.x;
		pos.y -= step.y;
		this._moveWood(node, node.getPosition(), pos, false);

		this._unblockMe.step.pop();
		this._updateStepLabel(this._unblockMe.step.size());
	},

	_updateGateLabel : function(gate) {
		let label = this._formNode.getChildByName("tb4", ivy.UILabelFNT);
		let s = (gate+1).toString().padStart(3,  "0");
		cc.log("当前关卡：%s",s);
		label.setString(s);
	},
	_updateStepLabel : function(step) {
		let label = this._formNode.getChildByName("tb5", ivy.UILabelFNT);
		let s = (step).toString().padStart(3,  "0");
		cc.log("当前步数：%s",s);
		label.setString(s);
	},
	_updateBestLabel : function(best) {
		let label = this._formNode.getChildByName("tb6", ivy.UILabelFNT);
		let s = (best).toString().padStart(3,  "0");
		cc.log("最佳步数：%s",s);
		label.setString(s);
	},
	_updateMagnifyingLabel : function() {
		let count = unblockme.Recorder.getMagnifyingCount();
		cc.log("放大镜数量：%d",count);
		let label = this._formNode.getChildByName("tb7", ivy.UILabelTTF);
		label.setString(count.toString());
	},
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	_gate : 0,
	_unblockMe : null,//cppsupport::UnblockMe

	_touchMoved : false,
	_touchBeganTime : 0,
	_touchStartPostion : null,//cocos2d::Vec2

	_layer : null,
});

//0表示自动移动红色木块，1表示手动移动红色木块
unblockme.GameScene.userMoveRedWood = 1;

unblockme.GameScene.create = function (form, space=null) {
	return new unblockme.GameScene(form, space);
};
